package cc.wsyw126.java.nowcoder.sword_offer;

import java.util.HashMap;
import java.util.LinkedList;

/**
 * Created by Administrator on 2017/4/18.
 * 请实现一个函数用来找出字符流中第一个只出现一次的字符。
 * 例如，当从字符流中只读出前两个字符"go"时，第一个只出现一次的字符是"g"。
 * 当从该字符流中读出前六个字符“google"时，第一个只出现一次的字符是"l"。
 */
public class FirstAppearingOnce {
    private HashMap<Character, Integer> map = new HashMap<>();
    private LinkedList<Character> list = new LinkedList<>();

    //Insert one char from stringstream
    public void Insert(char ch) {
        Integer integer = map.get(ch);
        if (integer == null) {
            list.add(ch);
            integer = 0;
        } else if (integer == 1) {
            list.remove(new Character(ch));
        }
        integer++;
        map.put(ch, integer);
    }

    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce() {
        if (list.isEmpty()) {
            return '#';
        }
        return list.getFirst();
    }

    public static void main(String[] args) {
        FirstAppearingOnce firstAppearingOnce = new FirstAppearingOnce();
        String s = "google";
        for (int i = 0; i < s.length(); i++) {
            firstAppearingOnce.Insert(s.charAt(i));
            char c = firstAppearingOnce.FirstAppearingOnce();
            System.out.println("c = " + c);
        }
    }
}
